package com.body.park.gateway.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author chaox-wu
 * @Date 2022/12/2
 * @Description:
 */
@Component
public class RedisCache {

    @Resource(type = RedisTemplate.class)
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 添加redis
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        this.redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 添加redis并设置过期时间
     * @param key
     * @param value
     * @param timeout
     * @param unit
     */
    public void set(String key, Object value, long timeout, TimeUnit unit) {
        this.redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    /**
     * 添加值
     * @param key
     * @param value
     * @param time
     */
    public void set(String key, Object value, Long time) {
        this.redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    /**
     * 获取redis的值
     * @param key
     * @return
     */
    public Object get(String key) {
        return this.redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除
     * @param key
     */
    public void delete(String key) {
        this.redisTemplate.delete(key);
    }

    /**
     * 查询key的生命周期
     * @param key redis 存数据的键
     * @return 默认单位秒，也可以自行传入单位
     */
    public long getKeyExpire(String key) {
        return redisTemplate.getExpire(key);
    }
}
